/* Copyright (C) 2010 Moritz Bitsch
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *
 * Author:
 *      Moritz Bitsch <moritzbitsch@googlemail.com>
 */

namespace Webappi {
	public class SessionHelper {
		public Session session { get; set; }
		private string cookieName;

		public SessionHelper(scgi.Request req, string cookieName) {
			this.cookieName = cookieName;

			var cookies = Cookie.get_cookies(req);
			var sessionCookie = cookies.lookup(this.cookieName);

			if (sessionCookie != null) {
				//already have a session cookie, lookup session
				session = Session.load(req, sessionCookie.val);
			}
		}

		/*
		 * Save the session and return the cookie
		 */
		public Cookie? save() {
			if (this.session != null) {
				var cookie = new Cookie();
				cookie.name = this.cookieName;
				cookie.val = this.session.sid;

				this.session.save();

				return cookie;
			}

			return null;
		}

		/*
		 * Delete the session and return "delete cookie"
		 */
		public Cookie? delete() {
			if (this.session != null) {
				this.session.delete();

				var cookie = new Cookie();
				cookie.name = this.cookieName;
				cookie.val = this.session.sid;
				cookie.delete = true;

				return cookie;
			}

			return null;
		}
	}
}